package com.sephiron.clocksynchronizer;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.EditText;

public class NameEditorFragment extends DialogFragment {

	public static String EXTRA_NAME;
	private String mCctvName;

	EditText cctvNameTextField;

	public NameEditorFragment() {
		// TODO Auto-generated constructor stub
	}

	public static NameEditorFragment newInstance(String name) {
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_NAME, name);

		NameEditorFragment fragment = new NameEditorFragment();
		fragment.setArguments(args);

		return fragment;
	}

	private void sendResult(int resultCode) {
		if (getTargetFragment() == null) {
			return;
		}

		Intent i = new Intent();
		i.putExtra(EXTRA_NAME, mCctvName);
		getTargetFragment().onActivityResult(getTargetRequestCode(),
				resultCode, i);
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		mCctvName = (String) getArguments().getSerializable(EXTRA_NAME);

		View v = getActivity().getLayoutInflater().inflate(
				R.layout.dialog_text_edit, null);

		cctvNameTextField = (EditText) v.findViewById(R.id.EditCctvName);
		cctvNameTextField.setText(mCctvName);
		cctvNameTextField.selectAll();
		cctvNameTextField.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence c, int start, int before,
					int count) {
				if (c.length() != 0) {
					mCctvName = c.toString();
				} else {
					mCctvName = getResources().getString(R.string.noname);
				}
			}

			public void beforeTextChanged(CharSequence c, int start, int count,
					int after) {
				// this space intentionally left blank
			}

			public void afterTextChanged(Editable c) {
				// this one too
			}
		});

		return new AlertDialog.Builder(getActivity())
				.setView(v)
				.setTitle(R.string.cctv_name)
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
							}
						})
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								sendResult(Activity.RESULT_OK);
							}
						}).create();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		getDialog().getWindow().setSoftInputMode(
				LayoutParams.SOFT_INPUT_STATE_VISIBLE);
	}
}
